﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SampleSite
{
    public class SimpleSiteMapMenu : CompositeDataBoundControl
    {

        private string _activeCssClass;

        public string ActiveItemCssClass
        {
            get { return _activeCssClass; }
            set { _activeCssClass = value; }
        }

        private string _itemCssClass;

        public string ItemCssClass
        {
            get { return _itemCssClass; }
            set { _itemCssClass = value; }
        }

        private List<SimpleMenuItem> GetChildMenuItems(SiteMapNode node, SiteMapNode current)
        {
            List<SimpleMenuItem> nodes = new List<SimpleMenuItem>();

            foreach (SiteMapNode child in node.ChildNodes)
            {
                SimpleMenuItem item = new SimpleMenuItem(child, GetCssClass(child, current));
                item.MenuItems = GetChildMenuItems(child, current);
                nodes.Add(item);
            }

            return nodes;
        }

        internal string GetCssClass(SiteMapNode node, SiteMapNode current)
        {
            if (node == current)
            {
                return _activeCssClass ?? _itemCssClass;
            }
            else
            {
                return _itemCssClass;
            }
        }

        protected override int CreateChildControls(IEnumerable dataSource, bool dataBinding)
        {
            int count = 0;
            SiteMapNode current = null;
            SiteMapNodeCollection nodes = dataSource as SiteMapNodeCollection;
            SiteMapDataSource siteMap = this.GetDataSource() as SiteMapDataSource;

            if (dataBinding && nodes != null)
            {
                if (siteMap != null)
                {
                    current = siteMap.Provider.CurrentNode;
                }

                foreach (SiteMapNode node in nodes)
                {
                    count++;
                    SimpleMenuItem item = new SimpleMenuItem(node, GetCssClass(node, current));
                    item.MenuItems = GetChildMenuItems(node, current);
                    Controls.Add(item);
                }
            }

            return count;
        }

        public override void RenderBeginTag(System.Web.UI.HtmlTextWriter writer)
        {
            writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID);
            writer.RenderBeginTag(HtmlTextWriterTag.Ul);
        }

        public override void RenderEndTag(System.Web.UI.HtmlTextWriter writer)
        {
            writer.RenderEndTag();
        }
    }
}